import {
  Form, Select, InputNumber, Button, Upload, Icon, Input, DatePicker, message, AutoComplete, Table, Divider,
} from 'antd';
import * as React from "react";


import styles from './PointAdd.css';
import {RuleDomain} from "../../business/rule/RuleDomain";
import RuleService from "../../business/rule/RuleService";
import PointService from "../../business/point/PointService";
import {RuleAddDomain} from "../../business/rule/RuleAddDomain";
const {  RangePicker } = DatePicker;


const columns = [{
  title: '用户UMID',
  dataIndex: 'umId',
  key: 'umId'
}, {
  title: '活动名称',
  dataIndex: 'activityName',
  key: 'activityName'
}, {
  title: '活动ID',
  dataIndex: 'activityId',
  key: 'activityId',
}, {
  title: '活动积分',
  dataIndex: 'points',
  key: 'points',
}, {
  title: '操作者',
  dataIndex: 'operator',
  key: 'operator',
}];

const getNowDate =()=>{
  const date = new Date();
  let month: string | number = date.getMonth() + 1;
  let strDate: string | number = date.getDate();

  if (month <= 9) {
    month = "0" + month;
  }

  if (strDate <= 9) {
    strDate = "0" + strDate;
  }

  return date.getFullYear() + "-" + month + "-" + strDate + " "
    + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}

class PointAdd extends React.Component{

  constructor(props){
    super(props)
    this.ruleService = new RuleService();
    this.updateRuleAdd = this.updateRuleAdd.bind(this);
    this.submitRuleAdd = this.submitRuleAdd.bind(this);
    this.addPointCallBack = this.addPointCallBack.bind(this);
  }
  ruleService:RuleService;
  state = {
    ruleDomain:new RuleDomain(),
    ruleAddList:[],
    ruleAddListCopy:[],
    loading:false,
  };

  show(ruleAddList:any[],loading:boolean){

    if(ruleAddList.length !=0){
      return (<Table columns={columns}
                     dataSource={ruleAddList}
                     rowKey={record=>record.id}
                     loading={loading}/>);
    }else{
      return "";
    }
  }

  updateRuleAdd(ruleAddListSub:RuleAddDomain[]){
    const {ruleAddList} = this.state;
    let length = ruleAddList.length;
    ruleAddListSub.map(
      (item,index)=>{
          item.id = length+index;
          ruleAddList.push(item);
      });
    this.setState({ruleAddList:ruleAddList,ruleAddListCopy:[]});

  }

  addPointCallBack(res,isSuccess,req){
    if(!isSuccess||res.code!='200') {
      message.info("添加失败" + req.umId);
      const {ruleAddListCopy} = this.state;
      ruleAddListCopy.push(req);
    }
   const {ruleAddList,ruleAddListCopy} = this.state;
    let value = ruleAddList.pop();
    if(value != undefined){
      const token  = sessionStorage.getItem("adminLoginToken");
      this.ruleService.addPoint(token,value,this.addPointCallBack);
      return;
    }
    this.setState({
      ruleAddList:ruleAddListCopy,
      loading:false,
    });
    this.closeLoading();
  }

  closeLoading:any;

  submitRuleAdd(call){
    const {ruleAddList} = this.state;
    if(ruleAddList.length ==0){
      message.info("清先输入信息");
      return;
    }
    this.closeLoading = call;
    const token  = sessionStorage.getItem("adminLoginToken");
    this.setState({loading:true});
    let value = ruleAddList.pop();
    if(value != undefined){
      this.ruleService.addPoint(token,value,this.addPointCallBack);
    }
  }

  render() {
    const {ruleAddList,loading} = this.state;
    return (
      <div className={styles.normal}>
        <div className={styles.search_header}>
          <HorizontalSearchForm updateRuleAdd={this.updateRuleAdd} appPoint={this.submitRuleAdd}/>
        </div>
        <div>
          {this.show(ruleAddList,loading)}
        </div>
      </div>
    );
  }
}

export default PointAdd;


interface RulePros{
  updateRuleAdd:any;
  appPoint:any;
}

class HorizontalSearchForm extends React.Component<RulePros,any> {
  componentDidMount() {
  }

  constructor(props) {
    super(props)
    this.pointService =new PointService();
    this.onSelect = this.onSelect.bind(this);
    this.handleSearch = this.handleSearch.bind(this);
    this.searchRuleRes = this.searchRuleRes.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.inputUsername = this.inputUsername.bind(this);
    this.addPoint = this.addPoint.bind(this);
    this.closeLoading = this.closeLoading.bind(this);
  }

  state = {
    ruleNameList: [],
    ruleName:'',
    username:'',
    loading:false,
  }


  handleSubmit(e){
    e.preventDefault();
    const {updateRuleAdd} = this.props;
    const {loading } = this.state;
    if(loading){
        return;
    }
    let ruleName = this.state.ruleName;
    let username = this.state.username;
    let adminUsername = sessionStorage.getItem('adminUsername');
    if(ruleName ==''){
      message.info("请输入规则名称");
      return;
    }
    if(username ==''){
      message.info("请输入用户UMID");
      return;
    }
    let ruleNameList = this.state.ruleNameList;
    let flag:boolean = false;
    ruleNameList.map((rule,index)=>{
        if(rule ==ruleName){
          flag = true;
        }
    });
    if(!flag){
      message.info("规则名称不存在"+ruleName);
      return;
    }
    let ruleAddList = [];
    let activity = ruleName.split('  ');
    let index = 0;
    username.split(',').forEach(value=>{
      let rule = new RuleAddDomain();
      rule.umId= value;
      rule.points=activity[2];
      rule.activityId=activity[0];
      rule.activityName=activity[1];
      rule.operateType='reward_points';
      rule.operateTime=getNowDate();
      rule.operator = adminUsername;
      ruleAddList.push(rule);
    });
    this.props.updateRuleAdd(ruleAddList);
  }
  pointService:PointService;
  handleSearch(value) {
    if(!value){
      return;
    }else{
      let token = sessionStorage.getItem('adminLoginToken');
      let username = sessionStorage.getItem('adminUsername');
      let host = sessionStorage.getItem(username+'_host');
      this.pointService.queryByHostLikeName(value,host,token,this.searchRuleRes);
    }
  }

  onSelect(value) {
    this.setState({
      ruleName: value,
    });
  }

  searchRuleRes(res,isSuccess){
    let ruleName = [];
    if(isSuccess&&res.code=="200"){
      res.data.map((item,index)=>{
        if(item.activeFlag){
          ruleName.push(item.activityId+"  "+item.activityName+"  "+item.points);
        }

      });
      this.setState({
        ruleNameList: !ruleName ? [] :ruleName,
      });
    }

  }
  inputUsername(e){
    this.setState({
      [e.target.name] :e.target.value,
    });
  }

  closeLoading(){
    this.setState({
      loading:false,
    });
  }

  addPoint(e){
    e.preventDefault();
    this.props.appPoint(this.closeLoading);
    this.setState({
      loading:true,
    });
  }

  render() {

    const { ruleNameList,loading } = this.state;
    return (
      <Form layout="inline" onSubmit={this.handleSubmit}>
        <div className={styles.search_username_input1}>
        <Form.Item
          label={"规则名称"}
        >
          <AutoComplete
            dataSource={ruleNameList}
            style={{ width: 200 }}
            onSelect={this.onSelect}
            onSearch={this.handleSearch}
            placeholder="输入规则名称"
          />
        </Form.Item>
        </div>
        <div className={styles.search_username_input2}>
        <Form.Item
          label={"用户UMID"}
        >
            <Input onChange={this.inputUsername} prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}  placeholder="username" name="username" />
        </Form.Item>
        </div>
        <div className={styles.search_username_input3}>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
          >
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            onClick={this.addPoint}
            loading={loading}
          >
            提交
          </Button>
        </Form.Item>
        </div>
      </Form>
    );
  }
}

